package com.ljq.provider;

import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.DeliveryMode;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageProducer;
import javax.jms.Queue;
import javax.jms.Session;
import javax.jms.TextMessage;

import org.apache.activemq.ActiveMQConnection;
import org.apache.activemq.ActiveMQConnectionFactory;

/**
 * jms是规范 mq是实现
 * 
 * @author linjq
 *
 */
public class ProviderImpl implements Provider {

	private static final String USERNAME = ActiveMQConnection.DEFAULT_USER;
	private static final String PASSWORD = ActiveMQConnection.DEFAULT_PASSWORD;
	private static final String BROKEURL = ActiveMQConnection.DEFAULT_BROKER_URL;

	ConnectionFactory connectionFactory;
	Connection connection;
	Session session;

	public void init() {
		try {
			// ConnectionFactory ：连接工厂，JMS 用它创建连接
			connectionFactory = new ActiveMQConnectionFactory(USERNAME, PASSWORD, BROKEURL);

			// Session： 一个发送或接收消息的线程
			connection = connectionFactory.createConnection();

			// 启动
			connection.start();

			// 获取操作连接
			session = connection.createSession(true, Session.SESSION_TRANSACTED);
		} catch (JMSException e) {
			e.printStackTrace();
		}

	}
	
	//绑定线程
	ThreadLocal<MessageProducer> t1 = new ThreadLocal<MessageProducer>();
	//发送的数量
	ThreadLocal<Integer> t1Cnt = new ThreadLocal<Integer>();

	public void sendMessage(String name) {

		try {
			// 获取队列，
			Queue queue = session.createQueue(name);

			//单线程
//			MessageProducer messageProducer = session.createProducer(queue);
			
			//多线程
			MessageProducer messageProducer;
			if(t1.get()!=null) {
				messageProducer = t1.get();
			} else {
				 messageProducer = session.createProducer(queue);
				 t1.set(messageProducer);
			}
			
			Integer cnt = t1Cnt.get();
			if(cnt==null) {
				cnt = 0;
			}
			cnt++;
			
System.out.println(222);
			for (int i = 0; i < 1000; i++) {

				TextMessage message = session.createTextMessage(Thread.currentThread().getName() + "：我是xx平台，我需要发送短信，短信内容yyyy" + "\t"+t1Cnt);

				System.out.println();

				messageProducer.send(message);

				// 设置不持久化，此处学习，实际根据项目决定
				messageProducer.setDeliveryMode(DeliveryMode.NON_PERSISTENT);

				// 发送后提交
				session.commit();
			}

		} catch (

		JMSException e) {
			e.printStackTrace();
		}
	}

}
